﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;

using LeadVinaglue.Models;
using LeadVinaglue.Models.ViewPages;
using LeadVinaglue.Utility;
using LeadVinaglue.Helpers;
using LeadVinaglue.Repository;

namespace LeadVinaglue.Repository
{
    public class ProductListManagementRepository : BaseRepository
    {
        public static string ProductImagesURL = ConfigurationManager.AppSettings["ProductImagesURL"].ToString();
        public static string ProductAttachURL = ConfigurationManager.AppSettings["ProductAttachURL"].ToString();
        public static int NumOfProductNotification = int.Parse(ConfigurationManager.AppSettings["NumOfProductNotification"].ToString());
        LeadVinaglueEntities entities = new LeadVinaglueEntities();

        public void GetModel(ref ProductViewModel model)
        {
            int intTotal=0;
            // Set value
            model.NavigationBar = GetCategoryItemLink(model.CategoryId, model.SubCategoryId);
            model.TopDocument = GetAllProductBy(1, ProductImagesURL, 1, 12);
            model.TopGallery = GetAllProductBy(3, ProductImagesURL, 1, 12);
            model.TopLinks = GetTopLink(model.FilterRawURL + "?sort={0}");
            model.Filters = GetFilterModel(model.FilterRawURL + "?fb={0}&fv={1}", model.Filters.LanguageSelected, model.Filters.DocumentSelected, model.Filters.TypeSelected);
            model.ProductList = GetAllProductDetails(model.CategoryId, model.SubCategoryId, model.FilterBy, model.FilterValue, ProductImagesURL, model.PageIndex, model.PageSize, model.SortOrder, ref intTotal);
            model.PaginateHtml = Helpers.Paginate.Pagination(model.RawURL + "&page={0}&sort=" + model.SortOrder, model.PageSize, model.PageIndex, intTotal);
            model.ShowingHtml = Helpers.Paginate.Showing(model.PageSize, model.PageIndex, intTotal);
        }

        public void GetModelSearch(ref ProductViewModel model)
        {
            int intTotal = 0;

            // Set value
            model.TopDocument = searchAllProductBy(1, model.FilterValue, ProductImagesURL, 1, 12);
            model.TopGallery = searchAllProductBy(3, model.FilterValue, ProductImagesURL, 1, 12);
            model.TopLinks = GetTopLink(model.FilterRawURL + "?fb=" + model.FilterBy + "&fv=" + model.FilterValue + "&sort={0}");
            model.Filters = GetFilterModel(model.FilterRawURL + "?fb={0}&fv={1}", model.Filters.LanguageSelected, model.Filters.DocumentSelected, model.Filters.TypeSelected);
            model.ProductList = GetAllFindByKeywords(model.FilterBy, model.FilterValue, ProductImagesURL, model.PageIndex, model.PageSize, model.SortOrder, ref intTotal);
            model.PaginateHtml = Helpers.Paginate.Pagination(model.RawURL + "&page={0}&sort=" + model.SortOrder, model.PageSize, model.PageIndex, intTotal);
            model.ShowingHtml = Helpers.Paginate.Showing(model.PageSize, model.PageIndex, intTotal);
        }
        public void GetModelTop(ref ProductViewModel model)
        {
            int intTotal = 0;
            // Set value
            model.NavigationBar = GetCategoryItemLink(0, 0);
            model.TopDocument = GetAllProductBy(1, ProductImagesURL, 1, 12);
            model.TopGallery = GetAllProductBy(3, ProductImagesURL, 1, 12);
            model.TopLinks = GetTopLink(model.FilterRawURL + "?sort={0}");
            model.Filters = GetFilterModel(model.FilterRawURL + "?fb={0}&fv={1}", model.Filters.LanguageSelected, model.Filters.DocumentSelected, model.Filters.TypeSelected);
            model.ProductList = GetAllProductDetails(model.CategoryId, model.SubCategoryId, model.FilterBy, model.FilterValue, ProductImagesURL, model.PageIndex, model.PageSize, model.SortOrder, ref intTotal);
            model.PaginateHtml = Helpers.Paginate.Pagination(model.RawURL + "&page={0}&sort=" + model.SortOrder, model.PageSize, model.PageIndex, intTotal);
            model.ShowingHtml = Helpers.Paginate.Showing(model.PageSize, model.PageIndex, intTotal);
        }

        public void GetModelProductDetail(ref ProductDetailViewModel model)
        {
            //int intTotal = 0;
            // Set value            
            model.ProductDetail = GetSingleProduct(model.ProductId);
            model.NavigationBar = GetCategoryItemLink(model.ProductDetail.CategoryId, model.ProductDetail.SubCategoryId);
            model.TopGallery = GetAllProductBy(2, ProductImagesURL, 1, 6);
            model.TopDocument = GetAllProductBy(1, ProductImagesURL, 1, 6);
            model.NewDocument = getNewProductBy(model.ProductDetail.CategoryId, ProductImagesURL, 1, 6);
        }
        
        #region Build
        private TopLinkModel GetTopLink(string url)
        {
            TopLinkModel model = new TopLinkModel();
            model.DownloadLink = string.Format(url, "download-nhieu");
            model.GalleryLink = string.Format(url, "bo-suu-tap");
            model.NewLink = string.Format(url, "moi-nhat");
            model.ViewLink = string.Format(url, "xem-nhieu");

            return model;
        }
        private FilterViewModel GetFilterModel(string url, string languageSelected, string documentSelected , string typeSelected)
        {
            FilterViewModel model = new FilterViewModel();
            model.LanguageList = GetAllLanguages(url);
            model.DocumentTypeList = GetAllDocumentTypes(url);
            model.TypeList = GetAllTypes(url);
            model.LanguageSelected = languageSelected;
            model.DocumentSelected = documentSelected;
            model.TypeSelected = typeSelected;
            if (languageSelected != "Tất cả ngôn ngữ")
            {
                model.LanguageSelected = GetLanguages(int.Parse(languageSelected));
            }
            if (documentSelected != "Tất cả các loại")
            {
                model.DocumentSelected = GetDocument(int.Parse(documentSelected));
            }
            model.TypeSelected = typeSelected;

            return model;
        }

        private List<ItemLink> GetAllLanguages(string url)
        {
            List<ItemLink> list = new List<ItemLink>();
            var languages = new LanguageRepository().GetAll();
            foreach (var item in languages)
            {
                ItemLink model = new ItemLink();
                model.LinkText = item.Title;
                model.LinkUrl = string.Format(url, "language", item.LanguageId);
                list.Add(model);
            }


            return list;
        }
        private string GetLanguages(int languageSelected)
        {
            var languages = new LanguageRepository().GetAll().Where(c => c.LanguageId == languageSelected).ToList();
            return languages[0].Title;
        }
        private string GetDocument(int documentSelected)
        {
            var documentTypes = new DocumentTypeRepository().GetAll().Where(c => c.TypeId == documentSelected).ToList();
            return documentTypes[0].Title;
        }
        private List<ItemLink> GetAllDocumentTypes(string url)
        {
            List<ItemLink> list = new List<ItemLink>();
            var documentTypes = new DocumentTypeRepository().GetAll();
            foreach (var item in documentTypes)
            {
                ItemLink model = new ItemLink();
                model.LinkText = item.Title;
                model.LinkUrl = string.Format(url, "type", item.TypeId);
                list.Add(model);
            }

            return list;
        }

        private List<ItemLink> GetAllTypes(string url)
        {
            List<ItemLink> list = new List<ItemLink>();
            ItemLink model;

            // Add models
            model = new ItemLink();
            model.LinkText = "DOC";
            model.LinkUrl = string.Format(url, "extension", "doc");
            list.Add(model);

            // Add models
            model = new ItemLink();
            model.LinkText = "PDF";
            model.LinkUrl = string.Format(url, "extension", "pdf");
            list.Add(model);

            // Add models
            model = new ItemLink();
            model.LinkText = "XLS";
            model.LinkUrl = string.Format(url, "extension", "xls");
            list.Add(model);

            // Add models
            model = new ItemLink();
            model.LinkText = "PPT";
            model.LinkUrl = string.Format(url, "extension", "ppt");
            list.Add(model);

            // Add models
            model = new ItemLink();
            model.LinkText = "RTF";
            model.LinkUrl = string.Format(url, "extension", "rtf");
            list.Add(model);

            // Add models
            model = new ItemLink();
            model.LinkText = "TXT";
            model.LinkUrl = string.Format(url, "extension", "txt");
            list.Add(model);

            return list;
        }

        private List<ProductItem> GetAllProductBy(int typeId, string productImageUrl, int pageIndex, int pageSize)
        {
            List<ProductItem> list = new List<ProductItem>();
            var products = (from c in entities.Products
                            join ca in entities.Categories on c.CategoryID equals ca.ID
                            where c.TypeId == typeId && c.Active == true
                            select new
                            {
                                ProductId = c.ID,
                                TypeId = c.TypeId,
                                Title = c.Title,
                                ImageUrl = c.ImageURL
                            }).ToList();

            products = products.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            // Add list
            foreach (var item in products)
            {
                ProductItem model = new ProductItem();
                model.Title = StringClearFormat.Clear35(item.Title);
                model.ImageUrl = (!string.IsNullOrEmpty(item.ImageUrl)) ? string.Format("{0}/{1}", productImageUrl, item.ImageUrl) : "/images/noimagemedium.jpg";
                model.LinkUrl = string.Format("/xem-tai-lieu/{0}.{1}.html", StringClearFormat.ClearSpecials(item.Title), item.ProductId);

                list.Add(model);
            }

            return list;
        }

        private List<ProductItem> searchAllProductBy(int typeId, string keywords, string productImageUrl, int pageIndex, int pageSize)
        {
            List<ProductItem> list = new List<ProductItem>();
            var products = (from c in entities.Products
                            join ca in entities.Categories on c.CategoryID equals ca.ID
                            where c.TypeId == typeId && c.Active == true && (c.FileName.IndexOf(keywords)>=0)
                            select new
                            {
                                ProductId = c.ID,
                                TypeId = c.TypeId,
                                Title = c.Title,
                                ImageUrl = c.ImageURL
                            }).ToList();

            products = products.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            // Add list
            foreach (var item in products)
            {
                ProductItem model = new ProductItem();
                model.Title = StringClearFormat.Clear35(item.Title);
                model.ImageUrl = (!string.IsNullOrEmpty(item.ImageUrl)) ? string.Format("{0}/{1}", productImageUrl, item.ImageUrl) : "/images/noimagemedium.jpg";
                model.LinkUrl = string.Format("/xem-tai-lieu/{0}.{1}.html", StringClearFormat.ClearSpecials(item.Title), item.ProductId);

                list.Add(model);
            }

            return list;
        }

        private List<ProductListItem> getNewProductBy(int categoryId, string productImageUrl, int pageIndex, int pageSize)
        {
            List<ProductListItem> list = new List<ProductListItem>();
            var products = (from c in entities.Products
                            where c.CategoryID == categoryId
                            select new
                            {
                                ProductId = c.ID,
                                TypeId = c.TypeId,
                                Title = c.Title,
                                ImageUrl = c.ImageURL,
                                Reviewed = c.Reviewed,
                                Downloaded = c.Downloaded,
                                FileType = c.FileType
                            }).ToList();

            products = products.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            // Add list
            foreach (var item in products)
            {
                ProductListItem model = new ProductListItem();
                model.Title = StringClearFormat.Clear35(item.Title);
                model.ImageUrl = (!string.IsNullOrEmpty(item.ImageUrl)) ? string.Format("{0}/{1}", productImageUrl, item.ImageUrl) : "/images/noimagemedium.jpg";
                model.LinkUrl = string.Format("/xem-tai-lieu/{0}.{1}.html", StringClearFormat.ClearSpecials(item.Title), item.ProductId);
                model.Reviewed = item.Reviewed == null ? 0 : item.Reviewed.Value;
                model.Downloaded = item.Downloaded == null ? 0 : item.Downloaded.Value;
                model.FileType = item.FileType;

                list.Add(model);
            }

            return list;
        }

        private List<ProductItem> GetAllProductInWeek(string productImageUrl, int pageIndex, int pageSize)
        {
            DateTime firstDate = LeadTools.GetFirstDateOfWeek(DateTime.Now.Date, DayOfWeek.Sunday);
            DateTime lastDate = LeadTools.GetLastDateOfWeek(DateTime.Now.Date, DayOfWeek.Saturday);
            lastDate = LeadTools.EndOfDay(lastDate);

            List<ProductItem> list = new List<ProductItem>();
            var products = (from c in entities.Products
                            where c.Active == true && c.DateCreated >= firstDate && c.DateCreated <= lastDate
                            orderby c.Reviewed descending
                            select new
                            {
                                ProductId = c.ID,
                                TypeId = c.TypeId,
                                Title = c.Title,
                                ImageUrl = c.ImageURL
                            }).ToList();

            products = products.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            // Add list
            foreach (var item in products)
            {
                ProductItem model = new ProductItem();
                model.Title = StringClearFormat.Clear35(item.Title);
                model.ImageUrl = (!string.IsNullOrEmpty(item.ImageUrl)) ? string.Format("{0}/{1}", productImageUrl, item.ImageUrl) : "/images/noimagemedium.jpg";
                model.LinkUrl = string.Format("/xem-tai-lieu/{0}.{1}.html", StringClearFormat.ClearSpecials(item.Title), item.ProductId);

                list.Add(model);
            }

            return list;
        }


        private List<ProductListItem> GetAllProductDetails(int CategoryId, int SubCategoryId, string filterBy, string filterValue, string productImageUrl, int pageIndex, int pageSize, string sort, ref int intTotal)
        {
            List<ProductListItem> list = new List<ProductListItem>();
            var products = (from c in entities.Products
                            join u in entities.UserSet on c.CreatedByUserID equals u.ID
                            join ca in entities.Categories on c.CategoryID equals ca.ID
                            where c.Active == true && c.IsPublic == true && u.IsApproved == true && u.IsLockedOut == false
                            select new
                            {
                                ProductId = c.ID,
                                CategoryID = c.CategoryID,
                                SubCategoryId = c.SubCategoryID,
                                TypeId = c.TypeId,
                                LanguageId = c.LanguageId,
                                DocumentTypeId = c.DocumentTypeId,
                                Title = c.Title,
                                ImageUrl = c.ImageURL,
                                LongDesc = c.LongDesc,
                                FileType = c.FileType,
                                CreatedByUserID = c.CreatedByUserID,
                                Fullname = u.Fullname,
                                Email = u.Email,
                                DateCreated = c.DateCreated,
                                Reviewed = c.Reviewed,
                                Downloaded = c.Downloaded,
                                Tags = c.Tags
                            }).ToList();
            if (CategoryId > 0)
            {
                products = products.Where(c => c.CategoryID == CategoryId).ToList();
            }

            if (SubCategoryId > 0)
            {
                products = products.Where(c => c.SubCategoryId == SubCategoryId).ToList();
            }

            if (!string.IsNullOrEmpty(filterBy))
            {
                if (filterBy.Equals("extension", StringComparison.OrdinalIgnoreCase))
                    products = products.Where(c => c.FileType.Contains(filterValue)).ToList();
                else
                {
                    int value = int.Parse(filterValue);
                    if (filterBy.Equals("language", StringComparison.OrdinalIgnoreCase))
                        products = products.Where(c => c.LanguageId == value).ToList();
                    else
                        products = products.Where(c => c.DocumentTypeId == value).ToList();

                }
            }

            //Total product
            intTotal = products.Count;

            //Sort
            if (sort == "moi-nhat")
            {
                products = products.OrderByDescending(c => c.DateCreated).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            else if (sort == "xem-nhieu")
            {
                products = products.OrderByDescending(c => c.Reviewed).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            else if (sort == "download-nhieu")
            {
                products = products.OrderByDescending(c => c.Downloaded).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            else if (sort == "bo-su-tap")
            {
                products = products.OrderByDescending(c => c.Reviewed).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                products = products.OrderByDescending(c => c.DateCreated).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }

            

            // Add list
            foreach (var item in products)
            {
                ProductListItem model = new ProductListItem();

                model.Title = StringClearFormat.Clear35(item.Title);
                model.ImageUrl = (!string.IsNullOrEmpty(item.ImageUrl)) ? string.Format("{0}/{1}", productImageUrl, item.ImageUrl) : "/images/noimagemedium.jpg";
                model.LinkUrl = string.Format("/xem-tai-lieu/{0}.{1}.html", StringClearFormat.ClearSpecials(item.Title), item.ProductId);
                model.LongDesc = StringClearFormat.Clear255(StringClearFormat.RemoveHtml(item.LongDesc));
                model.FileType = item.FileType;
                model.CreationDate = Convert.ToDateTime(item.DateCreated).ToString("dd-MM-yyyy");
                model.Reviewed = item.Reviewed == null ? 0 : item.Reviewed.Value;
                model.Downloaded = item.Downloaded == null ? 0 : item.Downloaded.Value;
                model.Username = item.Fullname;
                model.Tags = GetTagHTML(item.Tags);

                list.Add(model);
            }

            return list;
        }


        private List<ProductListItem> GetAllFindByKeywords(string filterBy, string filterValue, string productImageUrl, int pageIndex, int pageSize, string sort, ref int intTotal)
        {
            List<ProductListItem> list = new List<ProductListItem>();
            var products = (from c in entities.Products
                            join u in entities.UserSet on c.CreatedByUserID equals u.ID
                            join ca in entities.Categories on c.CategoryID equals ca.ID
                            where c.Active == true && c.IsPublic == true && u.IsApproved == true && u.IsLockedOut == false
                            select new
                            {
                                ProductId = c.ID,
                                SubCategoryId = c.SubCategoryID,
                                TypeId = c.TypeId,
                                LanguageId = c.LanguageId,
                                DocumentTypeId = c.DocumentTypeId,
                                Title = c.Title,
                                ImageUrl = c.ImageURL,
                                LongDesc = c.LongDesc,
                                FileType = c.FileType,
                                CreatedByUserID = c.CreatedByUserID,
                                Fullname = u.Fullname,
                                Email = u.Email,
                                DateCreated = c.DateCreated,
                                Reviewed = c.Reviewed,
                                Downloaded = c.Downloaded,
                                Tags = c.Tags
                            }).ToList();

            // Filter by
            if (!string.IsNullOrEmpty(filterBy))
            {
                if (filterBy.Equals("tags", StringComparison.OrdinalIgnoreCase))
                    products = products.Where(c => c.Tags.Contains(filterValue)).ToList();
                else if (filterBy.Equals("member", StringComparison.OrdinalIgnoreCase))
                {
                    products = products.Where(c => c.Fullname.Equals(filterValue, StringComparison.OrdinalIgnoreCase)).ToList();
                }
                else if (filterBy.Equals("book", StringComparison.OrdinalIgnoreCase))
                {
                    products = products.Where(c => c.Title.Contains(filterValue)).ToList();
                }
                else if (filterBy.Equals("extension", StringComparison.OrdinalIgnoreCase))
                    products = products.Where(c => c.FileType.Contains(filterValue)).ToList();
                else
                {
                    int value = int.Parse(filterValue);
                    if (filterBy.Equals("language", StringComparison.OrdinalIgnoreCase))
                        products = products.Where(c => c.LanguageId == value).ToList();
                    else
                        products = products.Where(c => c.DocumentTypeId == value).ToList();

                }
            }

            //Total product
            intTotal = products.Count;

            //Sort
            if (sort == "moi-nhat")
            {
                products = products.OrderByDescending(c => c.ProductId).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            else if (sort == "xem-nhieu")
            {
                products = products.OrderByDescending(c => c.Reviewed).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            else if (sort == "download-nhieu")
            {
                products = products.OrderByDescending(c => c.Downloaded).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            else if (sort == "bo-su-tap")
            {
                products = products.OrderByDescending(c => c.Reviewed).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                products = products.OrderByDescending(c => c.ProductId).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }            

            // Add list
            foreach (var item in products)
            {
                ProductListItem model = new ProductListItem();

                model.Title = StringClearFormat.Clear35(item.Title);
                model.ImageUrl = (!string.IsNullOrEmpty(item.ImageUrl)) ? string.Format("{0}/{1}", productImageUrl, item.ImageUrl) : "/images/noimagemedium.jpg";
                model.LinkUrl = string.Format("/xem-tai-lieu/{0}.{1}.html", StringClearFormat.ClearSpecials(item.Title), item.ProductId);
                model.LongDesc = StringClearFormat.Clear255(StringClearFormat.RemoveHtml(item.LongDesc));
                model.FileType = item.FileType;
                model.CreationDate = Convert.ToDateTime(item.DateCreated).ToString("dd-MM-yyyy");
                model.Reviewed = item.Reviewed == null ? 0 : item.Reviewed.Value;
                model.Downloaded = item.Downloaded == null ? 0 : item.Downloaded.Value;
                model.Username = item.Fullname;
                model.Tags = GetTagHTML(item.Tags);

                list.Add(model);
            }

            return list;
        }

        private ProductListItem GetSingleProduct(int productId)
        {
            var prod = (from c in entities.Products
                            where c.ID == productId && c.Active == true
                            join u in entities.UserSet on c.CreatedByUserID equals u.ID
                            join ca in entities.Categories on c.CategoryID equals ca.ID
                            join subca in entities.SubCategories on c.SubCategoryID equals subca.ID
                            select new
                            {
                                ProductId = c.ID,
                                TypeId = c.TypeId,
                                Title = c.Title,
                                ImageUrl = c.ImageURL,
                                AttachFile = c.FileName,
                                CreationDate = c.DateCreated,
                                Downloaded = c.Downloaded,
                                FileType = c.FileType,
                                SubCategoryId = c.SubCategoryID,
                                LanguageId = c.LanguageId,
                                DocumentTypeId = c.DocumentTypeId,
                                LongDesc = c.LongDesc,
                                CreatedByUserID = c.CreatedByUserID,
                                DateCreated = c.DateCreated,
                                Reviewed = c.Reviewed,
                                Tags = c.Tags,
                                Fullname = u.Fullname,
                                Email = u.Email,
                                CategoryId = c.CategoryID,
                                CategoryName = ca.Name,
                                SubCategoryName = subca.Name
                            }).FirstOrDefault();

           

            ProductListItem model = new ProductListItem();
            if (prod != null)
            {
                model.CreationDate = Convert.ToDateTime(prod.CreationDate).ToString("dd-MM-yyyy");
                model.Downloaded = prod.Downloaded == null ? 0 : prod.Downloaded.Value;
                model.FileType = prod.FileType;
                model.ImageUrl = (!string.IsNullOrEmpty(prod.ImageUrl)) ? string.Format("{0}/{1}", ProductImagesURL, prod.ImageUrl) : "/images/noimagemedium.jpg";
                model.AttachFile = (!string.IsNullOrEmpty(prod.AttachFile)) ? string.Format("{0}/{1}", ProductAttachURL, prod.AttachFile): string.Empty;
                model.LinkUrl = string.Format("/xem-tai-lieu/{0}.{1}.html", StringClearFormat.ClearSpecials(prod.Title), prod.ProductId);
                model.LongDesc = (!string.IsNullOrEmpty(prod.LongDesc)) ? prod.LongDesc : "";                
                model.Reviewed = prod.Reviewed == null ? 0 : prod.Reviewed.Value;
                model.Tags = GetTagHTML(prod.Tags);
                model.Title = prod.Title;
                model.Username = prod.Fullname;
                model.CategoryId = (int)prod.CategoryId;
                model.SubCategoryId = (int)prod.SubCategoryId;
                model.CategoryName = prod.CategoryName;
                model.SubCategoryName = prod.SubCategoryName;
                if (model.LongDesc.Length > 200)
                {
                    model.SortDesc = model.LongDesc.Substring(0, 200);
                }
                else
                {
                    model.SortDesc = model.LongDesc;
                }
                if (model.SortDesc.Length > 190)
                {
                    string[] str = model.SortDesc.Split(' ');
                    if(str.Length>1)
                    {
                        model.SortDesc = "";
                        for(int i=0;i<str.Length-1;i++)
                        {
                            model.SortDesc = model.SortDesc + str[i] + " ";
                        }
                    }
                    model.SortDesc = model.SortDesc + "...";
                }
            }


            return model;
        }

        private string GetTagHTML(string tags)
        {
            List<TagLinkItem> list = new List<TagLinkItem>();
            string html = string.Empty;

            if(!string.IsNullOrEmpty(tags))
            {
                string[] arr = tags.Split(',');
                for (int i = 0; i < arr.Length; i++)
                {
                    if (i > 0)
                        html += ", ";
                    html += string.Format("<a href='/search?fb=tags&fv={0}'>{1}</a>", arr[i], arr[i]);
                }
            }

            return html;
        }

        private List<CategoryItemLink> GetCategoryItemLink(int CategoryId, int subCategoryId)
        {
            List<CategoryItemLink> list = new List<CategoryItemLink>();
            List<SubCategoryItemLink> subs = new List<SubCategoryItemLink>();

            // 1. First - get all sub items
            using (SqlDataReader item = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringProfile, CommandType.StoredProcedure, "GetCategoryTotal"))
            {
                while (item.Read())
                {
                    SubCategoryItemLink model = new SubCategoryItemLink();
                    model.CategoryId = item.GetInt32(0);
                    model.Title = item.GetString(3);
                    model.LinkUrl = string.Format("/{0}/{1}.{2}.{3}", StringClearFormat.ClearSpecials(item.GetString(1)), StringClearFormat.ClearSpecials(item.GetString(3)), item.GetInt32(0), item.GetInt32(2));
                    model.Total = item.GetInt32(4);
                    if (item.GetInt32(2) == subCategoryId)
                    {
                        model.Selected = true;
                    }
                    subs.Add(model);
                }
            }

            // 2. Second - Get category
            var categories = new CategoryRepository().GetAll().OrderBy(c => c.Ordered).ToList();
            foreach (var item in categories)
            {
                CategoryItemLink model = new CategoryItemLink();
                if (item.ID == CategoryId)
                {
                    model.Selected = true;
                    model.SubItems = subs.Where(c => c.CategoryId == item.ID).ToList();
                }
                model.Title = item.Name;
                model.LinkUrl = string.Format("/{0}/tat-ca-tai-lieu.{1}", StringClearFormat.ClearSpecials(item.Name), item.ID);
                model.Total = subs.Where(c => c.CategoryId == item.ID).Sum(c => c.Total);
                list.Add(model);
            }           

            return list;
        }

        #endregion
    }
}